﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerGames.FarseerPhysics.Mathematics;
using FreeGoo.GameEngine.Renderables.Links;
using FarseerGames.FarseerPhysics;

namespace FreeGoo.GameEngine.Renderables.Particles.States
{
    public class AbsorbedByLink : ParticleState
    {
        private ILinkable _linkParent1;
        private ILinkable _linkParent2;
        private Link _link;

        public AbsorbedByLink(Particle particle, ILinkable linkParent1, ILinkable linkParent2, Link link)
            : base(particle)
        {
            ParticleSelectableInState = true;
            _linkParent1 = linkParent1;
            _linkParent2 = linkParent2;
            _link = link;
        }

        public override CollisionCategory StateCollissionCatagory { get { return Engine.LinkedParticleCollisionCategory; } }
        public override CollisionCategory StateCollidesWith { get { return CollisionCategory.None; } }
        
        public override void PerformStatePhysicsAction()
        {
            if (!_linkParent1.ContainsLink(_link))
            {
                Particle.State = new FreeFall(Particle);
                return;
            }

            Vector2 linkCenter = _link.Position;
            _linkParent1.Body.ApplyForceAtWorldPoint(Particle.Engine.PhysicsSimulator.Gravity * Particle.Body.Mass * 0.5f, linkCenter);
            _linkParent2.Body.ApplyForceAtWorldPoint(Particle.Engine.PhysicsSimulator.Gravity * Particle.Body.Mass * 0.5f, linkCenter);
        }

        public override void EnteringState()
        {
            base.EnteringState();
            Particle.ClearRenderer();
            Particle.RemoveFromPhysicsSimulator();
        }

        public override void ExitingState()
        {
            base.ExitingState();
            Particle.Body.Position = _link.Position;
            Particle.SetRenderer();
            Particle.AddToPhysicsSimulator();
        }
    }
}
